package com.sltx.controller;

import com.sltx.controller.base.BaseController;
import com.sltx.util.Conversion;
import com.sltx.util.HttpUtils;
import com.sltx.util.PageData;
import com.sltx.vo.PostJsonParam;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.Key;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
@RequestMapping(value="/evaluate")
public class EntBigDataEvaluateController extends BaseController {
	

	/**
	 * 
	 */
	private static final long serialVersionUID = -1780088092942641337L;

//	@Resource(name = "menusService")
//    MenusService menusService;
//
//	@Autowired
//    MemCacheService memCacheService;
	
    final static String STARTROW = "0";
    final static String ENDROW = "10";
    final static String MEMCACHE__PRE = "bigData";
    final static String PAGENO = "1";
    final static String PAGESIZE = "10";
	
//	@SuppressWarnings("unchecked")
//	@RequestMapping(value="evaluateAll", produces=MediaType.APPLICATION_JSON_VALUE+";charset=utf-8")
//	@ResponseBody
//	public Object evaluate(HttpServletRequest request,String entName){
//
//		Map<String, Object> resultMap = new HashMap<String, Object>();
//
//        PageData pd = this.getPageData();
//        Map<String, String> params = new LinkedHashMap<String, String>();
//
//        Map<String, String> paramMap = new HashMap<String, String>();
//        if(pd.getString("entName")!=null){
//            params.put("entName", Conversion.codeConversion(pd.getString("entName")));
//            entName = Conversion.codeConversion(pd.getString("entName"));
//        }else{
//        	params.put("entName", "北京天地互连信息技术有限公司");
//        	entName="龙信数据（北京）有限公司";
//        }
//        if(pd.getString("pageNo")!=null){
//        	params.put("pageNo", pd.getString("pageNo"));
//        }else{
//        	params.put("pageNo", "1");
//        }
//        if(pd.getString("pageSize")!=null){
//        	params.put("pageSize", pd.getString("pageSize"));
//        }else{
//        	params.put("pageSize", "200");
//        }
//		//股东及出资信息  getShareHolderInfo 当前公司的 股东公司
//		JSONObject shareHolderInfo = getEvaluationData("getShareHolderInfo", params); //INV
//
//    	resultMap.put("shareHolderInfo", getRegisterInfo(shareHolderInfo,"getShareHolderInfo"));
//
//        // 企业对外投资 getInvestmentAbroadInfo  (被投资企业)
//		JSONObject evaluationData = getEvaluationData("getInvestmentAbroadInfo", params); //ENTNAME
//        if(evaluationData !=null)
//        	resultMap.put("InvestmentAbroadInfo", getRegisterInfo(evaluationData,"getInvestmentAbroadInfo"));
//
//        // 法人代表对外投资（lawPersonInvestmentInfo）
//        JSONObject lawPersonInvestmentInfo = getEvaluationData("lawPersonInvestmentInfo", params);//ENTNAME
//        if(lawPersonInvestmentInfo !=null)
//            resultMap.put("lawPersonInvestmentInfo",getRegisterInfo(lawPersonInvestmentInfo,"lawPersonInvestmentInfo"));
//
//        //主要管理人员对外投资（mainPersonInvestmentInfo）
//        JSONObject mainPersonInvestmentInfo = getEvaluationData("mainPersonInvestmentInfo", params);//ENTNAME
//        if(mainPersonInvestmentInfo !=null)
//            resultMap.put("mainPersonInvestmentInfo",getRegisterInfo(mainPersonInvestmentInfo,"mainPersonInvestmentInfo"));
//
//		Object cb = 	request.getParameter("callback");
//		String result = Conversion.convertJsonString(null,resultMap,cb);
//
//        return result;
//
//	}



    /**
     * 调用 量子数聚接口（综合评价查询） 单项财务指标评价
     * @param request （前端是encode）
     * @param entName(企业名称）
     * @return
     * @throws Exception
     
    @RequestMapping(value = "/getEvaluatEion", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Map getEvaluatEion(HttpServletRequest request,String entName) throws Exception{ 

        Map<String, Object> resultMap = new HashMap<String, Object>();
       
        /*正式
         * Map<String, String> params = new LinkedHashMap<String, String>();
        params.put("entName", Conversion.codeConversion(entName);
        
       //测试
        Map<String, String> params = new LinkedHashMap<String, String>();
        params.put("entName", Conversion.codeConversion("龙信数据（北京）有限公司"));

        //（全国评价-按企业名称查询) areaP
        JSONObject areaObj = getEvaluationData("getNationalSingleFinanIndexEvaluByEntname", params);
        if(areaObj !=null)
        	resultMap.put("全国评价", areaObj);
        
        //（行业评价-按企业名称查询) industryObj
        JSONObject industryObj = getEvaluationData("getIndustrySingleFinanIndexEvaluByEntname", params);
        if(industryObj !=null)
            resultMap.put("行业评价", industryObj);
        
        //（地区评价-按企业名称查询) nationalObj
        JSONObject nationalObj = getEvaluationData("getFinancialIndexOfAddressInfoByEntname", params);
        if(nationalObj !=null)
            resultMap.put("地区评价", nationalObj);
        
        List<String> listEnts = new ArrayList<String>();
        
        
        return resultMap;
    }*/
    
    
    
    /**
     * 股东及出资信息
     * @param request
     * @param entName
     * @return
     */
	@SuppressWarnings("unchecked")
	//@RequestMapping(value="shareHolderInfo", produces=MediaType.APPLICATION_JSON_VALUE+";charset=utf-8")
	@ResponseBody
	public Object getShareHolderInfo(HttpServletRequest request,String entName){
		Map<String, Object> resultMap = new HashMap<String, Object>();
        PageData pd = this.getPageData();
        
        //Map<String, Object> params = requestName(pd);
        //PageData map = new PageData();
        //map.put("entName", params.get("entName"));
        pd.put("entName", Conversion.codeConversion(pd.getString("entName")));
		//股东及出资信息  getShareHolderInfo 当前公司的 股东公司
		JSONObject shareHolderInfo = getEvaluationData("getShareHolderInfo", pd); //INV
		Map<String,Object> pageInfo = (Map<String, Object>) shareHolderInfo.get("PAGEINFO");
		List<Object> resultList1 = getRegisterInfo(shareHolderInfo,"getShareHolderInfo");
		List<Object> resultList2 = new ArrayList<Object>();
		Integer pageSize = Integer.parseInt(pd.get("pageSize").toString());
		Integer pageNo =  Integer.parseInt(pd.get("pageNo").toString());
		for(int i=pageNo-1;i<pageSize;i++){
			try {
				resultList2.add(resultList1.get(i));
			} catch (Exception e) {
				
			}
		}
		
		if(resultList1.size()>0){
			pageInfo.put("TOTAL_COUNT",Integer.parseInt(pageInfo.get("TOTAL_COUNT").toString())-(pageSize -resultList1.size()));
		}else if(resultList1.size()<=0){
			pageInfo.put("TOTAL_COUNT", "0");
		}
		resultMap.put("shareHolderInfo", resultList1);
    	
    	//resultMap.put("size", resultList1.size());
    	resultMap.put("pageInfo", pageInfo);
    	
		Object cb = 	request.getParameter("callback"); 
		String result = Conversion.convertJsonString(null,resultMap,cb);
		
        return result;
		
	}
	
	/**
	 * 企业对外投资
	 * @param request
	 * @param entName
	 * @return
	 */
//	@SuppressWarnings("unchecked")
//	@RequestMapping(value="InvestmentAbroadInfo", produces=MediaType.APPLICATION_JSON_VALUE+";charset=utf-8")
//	@ResponseBody
//	public Object getInvestmentAbroadInfo(HttpServletRequest request,String entName){
//		Map<String, Object> resultMap = new HashMap<String, Object>();
//        PageData pd = this.getPageData();
//
//        //Map<String,Object> params = requestName(pd);
//        //PageData map = new PageData();
//        //map.put("entName", params.get("entName"));
//        pd.put("entName", Conversion.codeConversion(pd.getString("entName")));
//        // 企业对外投资 getInvestmentAbroadInfo  (被投资企业)
//		JSONObject evaluationData = getEvaluationData("getInvestmentAbroadInfo", pd); //ENTNAME
//		Map<String,Object> pageInfo = (Map<String, Object>) evaluationData.get("PAGEINFO");
//		System.out.println(evaluationData);
//        if(evaluationData !=null){
//        	List<Object> InvestmentAbroadInfo = getRegisterInfo(evaluationData,"getInvestmentAbroadInfo");
//        	resultMap.put("InvestmentAbroadInfo", InvestmentAbroadInfo);
//        	//resultMap.put("size", InvestmentAbroadInfo.size());
//        }
//
//    	resultMap.put("pageInfo", pageInfo);
//		Object cb = 	request.getParameter("callback");
//		String result = Conversion.convertJsonString(null,resultMap,cb);
//
//        return result;
//
//	}
	
	/**
	 * 法人代表对外投资
	 * @param request
	 * @param entName
	 * @return
	 */
	@SuppressWarnings("unchecked")
	//@RequestMapping(value="lawPersonInvestmentInfo", produces=MediaType.APPLICATION_JSON_VALUE+";charset=utf-8")
	@ResponseBody
	public Object lawPersonInvestmentInfo(HttpServletRequest request,String entName){
		Map<String, Object> resultMap = new HashMap<String, Object>();
        PageData pd = this.getPageData();

        //Map<String,Object> params = requestName(pd);
        //PageData map = new PageData();
       // map.put("entName", params.get("entName"));

        pd.put("entName", Conversion.codeConversion(pd.getString("entName")));
        // 法人代表对外投资（lawPersonInvestmentInfo） 
        JSONObject lawPersonInvestmentInfo = getEvaluationData("lawPersonInvestmentInfo", pd);//ENTNAME
		Map<String,Object> pageInfo = (Map<String, Object>) lawPersonInvestmentInfo.get("PAGEINFO");
        if(lawPersonInvestmentInfo !=null){
        	List<Object> lawPersonInvestment = getRegisterInfo(lawPersonInvestmentInfo,"lawPersonInvestmentInfo");
            resultMap.put("lawPersonInvestmentInfo",lawPersonInvestment);
            //resultMap.put("size",lawPersonInvestment.size());
		}

    	resultMap.put("pageInfo", pageInfo);
		Object cb = 	request.getParameter("callback"); 
		String result = Conversion.convertJsonString(null,resultMap,cb);
		
        return result;
		
	}
	
	/**
	 * 主要管理人员对外投资
	 * @param request
	 * @param entName
	 * @return
	 */
	@SuppressWarnings("unchecked")
	//@RequestMapping(value="mainPersonInvestmentInfo", produces=MediaType.APPLICATION_JSON_VALUE+";charset=utf-8")
	@ResponseBody
	public Object mainPersonInvestmentInfo(HttpServletRequest request,String entName){
		Map<String, Object> resultMap = new HashMap<String, Object>();
        PageData pd = this.getPageData();
        
        //Map<String,Object> params = requestName(pd);
        //PageData map = new PageData();
        //map.put("entName", params.get("entName"));
        pd.put("entName", Conversion.codeConversion(pd.getString("entName")));
		//主要管理人员对外投资（mainPersonInvestmentInfo）
        JSONObject mainPersonInvestmentInfo = getEvaluationData("mainPersonInvestmentInfo", pd);//ENTNAME
		Map<String,Object> pageInfo = (Map<String, Object>) mainPersonInvestmentInfo.get("PAGEINFO");
        if(mainPersonInvestmentInfo !=null){
        	List<Object> mainPersonInvestment = getRegisterInfo(mainPersonInvestmentInfo,"mainPersonInvestmentInfo");
            resultMap.put("mainPersonInvestmentInfo",mainPersonInvestment);
            //resultMap.put("size",mainPersonInvestment.size());
        }
        resultMap.put("pageInfo", pageInfo);
		Object cb = 	request.getParameter("callback"); 
		String result = Conversion.convertJsonString(null,resultMap,cb);
		
        return result;
		
	}
	
	/**
	 * 判断输入参数是否为空
	 * @param pd
	 * @return
	 */
	public Map<String,Object> requestName(Map<String,Object> pd){
		Map<String,Object> map = new HashMap<String, Object>();
		if(pd.get("entName")!=null){
			map.put("entName", Conversion.codeConversion(pd.get("entName").toString()));
        }else{
        	map.put("entName", "北京天地互连信息技术有限公司");
        }
        if(pd.get("pageNo")!=null){
        	map.put("pageNo", pd.get("pageNo").toString());
        }else{
        	map.put("pageNo", "1");
        }
        if(pd.get("pageSize")!=null){
        	map.put("pageSize", pd.get("pageSize").toString());
        }else{
        	map.put("pageSize", "200");
        }
		return map;
	}
	
	public List<Object> getRegisterInfo(JSONObject jsonObject,String tagC){
        PageData params = new PageData();
        List<Object> rstList = new ArrayList<Object>();
        
        for (int i = 0; i < getData(jsonObject).size(); i++) {
			JSONObject json =  (JSONObject) getData(jsonObject).get(i);
			
			String name =null;
			String type = null;
			
			if(tagC.equals("getShareHolderInfo")){//有分页信息
				
				if(json.getString("INVTYPE").toString().equals("自然人股东")||json.getString("INVTYPE").toString().equals("自然人")) {
					continue;
				}
				
				name = json.getString("INV").toString();
				type = "股东及出资信息";
				
			}else if(tagC.equals("getInvestmentAbroadInfo")){//有分页信息

				name = json.getString("ENTNAME").toString();
				type = "企业对外投资";
				
			}else if(tagC.equals("lawPersonInvestmentInfo")){//有分页信息
				
				name = json.getString("ENTNAME").toString();
				type = "法人代表对外投资";
				
			}else if(tagC.equals("mainPersonInvestmentInfo")){ //有分页信息
				
				name = json.getString("ENTNAME").toString();
				type = "主要管理人员对外投资";
			}
			
			if(name!=null && !name.equals("")){
		        params.put("entName",name);
			}
			params.put("pageNo", "1");
        	params.put("pageSize", "10");
        	
	        JSONObject jsonObjectTemp = Conversion.getServiceData("getRegisterInfo", params);//无分页信息
	        JSONObject jsonObjectTag = Conversion.getServiceData("getEntLable",params);//有分页信息
	        JSONArray jsonArrayTag = getData(jsonObjectTag);
			JSONArray jsonArray = getData(jsonObjectTemp);
			
			String tag = "";
			if(jsonArrayTag!=null & jsonArrayTag.size()>0){
				for(int j = 0;j<jsonArrayTag.size();j++){
					Map<String,Object> joTemp = (Map) jsonArrayTag.get(j);
					tag += joTemp.get("TAG")+"、";
				}
			}
			
			if(jsonArray!=null && jsonArray.size()>0){
				for(int k = 0;k<jsonArray.size();k++){
					Map<String,Object> joTemp = (Map) jsonArray.get(k);
					joTemp.put("TYPE", type);
					joTemp.put("TAG", tag);
					rstList.add(joTemp);
				}
			}
		}
        
        return rstList;
	}
	
	public JSONArray getData(JSONObject json){
		//RESULTDATA
		JSONArray array = null;
		 if (json.containsKey("RESULTDATA")) {
			 array = json.getJSONArray("RESULTDATA");
		 }
		return array;
	}
	
	
	 public static JSONObject getEvaluationData(String service,Map<String, String> params){
	        Key key = null;
			try {
                //key = Conversion.getLocalKey(Conversion.keyPath + "public_" + Conversion.CONIG_KEY_UID + ".key");
				key = Conversion.getConfigurationKey(Conversion.CONIG_KEY_NAME);
			} catch (Exception e) {
				e.printStackTrace();
			}
	    	 PostJsonParam jsonParam = new PostJsonParam();
	         jsonParam.setUid(Conversion.CONIG_KEY_UID);
	         jsonParam.setService(service);
	         jsonParam.setParams(params);
	         HttpUtils httpUtils = new HttpUtils(key);
	         String result = httpUtils.sendRequest(jsonParam);
	         return JSONObject.fromObject(result);
	    }


	   //远程调用
		public static Object interfaceDemo(String path, String data) {
			String result = "";

			try {
				URL url = new URL(path);
				HttpURLConnection conn = (HttpURLConnection)url.openConnection();
				PrintWriter out = null;
				conn.setRequestProperty("accept", "*/*");
				conn.setRequestProperty("connection", "Keep-Alive");
				conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
				conn.setDoOutput(true);
				conn.setDoInput(true);
				out = new PrintWriter(conn.getOutputStream());
				out.print(data);
				out.flush();
				InputStream is = conn.getInputStream();
				BufferedReader br = new BufferedReader(new InputStreamReader(is));

				String str;
				while((str = br.readLine()) != null) {
					result = result + str;
					System.out.println(result);
				}

				is.close();
				conn.disconnect();
			} catch (Exception var9) {
				var9.printStackTrace();
			}

			return result;
		}
		/**
		 * 股东及出资信息
		 * @param request
		 * @param entName
		 * @return
		 */
		@SuppressWarnings("unchecked")
		@RequestMapping(value="shareHolderInfo", produces=MediaType.APPLICATION_JSON_VALUE+";charset=utf-8")
		@ResponseBody
		public Object getShareHolderInfo(@RequestParam(required = false) String entName, @RequestParam(required = false) String pageSize, @RequestParam(required = false) String pageNo){
			String data = "entName="+ entName + "&pageSize="+pageSize + "&pageNo="+pageNo;
			return interfaceDemo("http://192.202.58.9:18052/sjs_product/evaluate/shareHolderInfo?",data);
		}
		/**
		 * 法人代表对外投资
		 * @param request
		 * @param entName
		 * @return
		 */
		@SuppressWarnings("unchecked")
		@RequestMapping(value="lawPersonInvestmentInfo", produces=MediaType.APPLICATION_JSON_VALUE+";charset=utf-8")
		@ResponseBody
		public Object lawPersonInvestmentInfo(@RequestParam(required = false) String entName){
			String data = "entName="+ entName;
			return interfaceDemo("http://192.202.58.9:18052/sjs_product/evaluate/lawPersonInvestmentInfo?",data);
		}

		/**
		 * 主要管理人员对外投资
		 * @param request
		 * @param entName
		 * @return
		 */
		@SuppressWarnings("unchecked")
		@RequestMapping(value="mainPersonInvestmentInfo", produces=MediaType.APPLICATION_JSON_VALUE+";charset=utf-8")
		@ResponseBody
		public Object mainPersonInvestmentInfo(@RequestParam(required = false) String entName){
			String data = "entName="+ entName;
			return interfaceDemo("http://192.202.58.9:18052/sjs_product/evaluate/mainPersonInvestmentInfo?",data);
		}

	}




